package com.lab.idea.bl.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.lab.idea.bl.entity.ExcelJoin;
import com.lab.idea.bl.entity.ExcelOut;
import com.lab.idea.bl.mapper.ExcelJoinMapper;
import com.lab.idea.bl.service.ExcelJoinService;
import com.lab.idea.common.exception.LabException;
import com.lab.idea.common.query.LabQuery;
import com.lab.idea.mybatis.service.impl.LabServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * excel关联 服务实现类
 * </p>
 *
 * @author lab
 * @since 2023-11-08
 */
@Service
public class ExcelJoinServiceImpl extends LabServiceImpl<ExcelJoinMapper, ExcelJoin> implements ExcelJoinService {

    @Override
    protected boolean saveCheck(ExcelJoin entity) {
        if (StrUtil.isBlankIfStr(entity.getOutId())) {
            throw new LabException("未选择输出");
        }
        if (StrUtil.isBlankIfStr(entity.getSheetName())) {
            throw new LabException("关联表头为空");
        }
        if (StrUtil.isBlankIfStr(entity.getMatchColumn())) {
            throw new LabException("匹配表头为空");
        }
        JSONArray array = JSONUtil.parseArray(entity.getMatchColumn());
        if (array.size() == 0) {
            throw new LabException("匹配表头为空");
        }
        LabQuery labQuery = new LabQuery();
        labQuery.eq("outId",entity.getOutId()).eq("sheetName",entity.getSheetName());
        List<ExcelJoin> list = query(labQuery);
        if (!CollUtil.isEmpty(list)) {
            for (ExcelJoin excelJoin : list) {
                if (!StrUtil.equals(excelJoin.getJoinId(),entity.getJoinId())) {
                    throw new LabException(String.format("%s 已关联",entity.getSheetName()));
                }
            }
        }
        return true;
    }
}
